package com.javabase.y2022.m04.day0423.v0067;

/**
 * @descriptions: Solution
 * @author: Tom
 * @date: 2022/4/23 上午 10:06
 * @version: 1.0
 */
public class Solution {
    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.addBinary("11", "1"));
    }
    public String addBinary(String a, String b){
        int aLength = a.length();
        int bLength = b.length();
        int deltaLength = Math.abs(a.length() - bLength);
        int newLength = aLength;
        StringBuffer stringBuffer = new StringBuffer();
        for(int i = 0; i < deltaLength; i++){
            stringBuffer.append('0');
        }
        if(aLength < bLength){
            a = stringBuffer.append(a).toString();
            newLength = bLength;
        } else {
            b = stringBuffer.append(b).toString();
            newLength = aLength;
        }
        StringBuffer ans = new StringBuffer();
        char label = '0';
//        char ch = '0';
        for (int i = newLength - 1; i >= 0; i--) {
            int tmpA = charToInt(a.charAt(i));
            int tmpB = charToInt(b.charAt(i));
            int tmpC = charToInt(label);
            int tmp = tmpA + tmpB + tmpC;
            if(tmp <= 1){
              label = '0';
              ans.append(tmp);
            }else if(tmp == 2){
                label = '1';
                ans.append('0');
            } else {
                label = '1';
                ans.append('1');
            }
        }
        ans = ans.reverse();
        if( label == '1'){
          return   '1' + ans.toString();
        }
        return ans.toString();
    }
    public int charToInt(char ch){
        int to = -1;
        if(ch == '0'){
            to = 0;
        }
        if(ch == '1'){
            to = 1;
        }
        return to;
    }
}
